package cn.stylefeng.guns.modular.task.controller;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.CangGuanRoleId;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.core.util.QRCodeUtil;
import cn.stylefeng.guns.core.util.QRCodeUtil2;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicOperate;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicOperateService;
import cn.stylefeng.guns.modular.task.entity.TaskOrder;
import cn.stylefeng.guns.modular.task.model.params.TaskDetailedParam;
import cn.stylefeng.guns.modular.task.model.params.TaskOrderParam;
import cn.stylefeng.guns.modular.task.model.result.TaskDetailedResult;
import cn.stylefeng.guns.modular.task.service.TaskDetailedService;
import cn.stylefeng.guns.modular.task.service.TaskOrderService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;


/**
 * 作业单表控制器
 */
@Controller
@RequestMapping("/taskOrder")
public class TaskOrderController extends BaseController {

    private String PREFIX = "/task/taskOrder";

    @Autowired
    private TaskOrderService taskOrderService;

    @Autowired
    private UserService userService;

    /**
     * 跳转到主页面
     */
    @RequestMapping("")
    public String index(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/taskOrder.html";
    }

    /**
     * 跳转到查询页面
     */
    @RequestMapping("queryTaskOrder")
    public String queryTaskOrder(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/queryTaskOrder.html";
    }

    /**
     * 跳转到服务卡页面
     */
    @RequestMapping("taskCard")
    public String taskCard(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/taskCard.html";
    }

    /**
     * 跳转到异常处理列表
     */
    @RequestMapping("taskAbnormal")
    public String taskAbnormal(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/taskAbnormal.html";
    }

    /**
     * 跳转到异常处理页面
     */
    @RequestMapping("toAbnormal")
    public String toAbnormal() {
        return PREFIX + "/abnormal.html";
    }

    @Autowired
    private TaskDetailedService taskDetailedService;
    
    /**
     *异常处理
     * @throws ParseException 
     */
    @RequestMapping("/abnormal")
    @ResponseBody
    public ResponseData abnormal(TaskOrderParam taskOrderParam) throws ParseException {
    	User user = userService.getcurrentUser();
    	String EndTime = taskOrderParam.getEndTime();
    	if(ToolUtil.isEmpty(EndTime)) {
    		return ResponseData.error("请选择结束时间！");
    	}
    	BigDecimal as = new BigDecimal(0);
    	taskOrderParam.setEndTime(EndTime);
    	taskOrderParam.setEndName(user.getName());
    	
    	TaskOrder taskOrder = taskOrderService.getById(taskOrderParam.getId());
    	BigDecimal hours = new BigDecimal(0);//工时
    	BigDecimal prescription = new BigDecimal(0);//时效
    	TaskDetailedParam taskDetailedParam = new TaskDetailedParam();
    	taskDetailedParam.setTaskId(Long.parseLong(taskOrder.getId().toString()));
    	List<TaskDetailedResult> list = taskDetailedService.findListBySpec(taskDetailedParam);
    	for (TaskDetailedResult r : list) {//合计总工时
			r.setEndTime(EndTime);
			BigDecimal h = new BigDecimal(DateUtil.getDatePoorMin(EndTime, r.getStartTime()));//计算个人工时
			hours = hours.add(h);
			r.setHours(h.toString());
			if(taskOrder.getSettlementMode().equals("工时")) {
				ToolUtil.copyProperties(r, taskDetailedParam);
				taskDetailedService.update(taskDetailedParam);
			}
		}
    	
    	if(taskOrder.getSettlementMode().equals("体积")) {//计算时效
    		if (list.size() >0) {
    			if (ToolUtil.isNotEmpty(taskOrder.getVolume())) {
    				BigDecimal volume = new BigDecimal(taskOrder.getVolume());
    				if(volume.compareTo(as)==1) {
    					prescription = volume.divide(hours,2,BigDecimal.ROUND_HALF_DOWN);
        				for (TaskDetailedResult r : list) {
        					BigDecimal h = new BigDecimal(r.getHours());
    						r.setVolume(prescription.multiply(h).setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());
    						ToolUtil.copyProperties(r, taskDetailedParam);
    						taskDetailedService.update(taskDetailedParam);
    					}
    				}
    			}
			}
    	}
    	if(taskOrder.getSettlementMode().equals("数量")) {//计算时效
    		if (list.size() >0) {
    			if (ToolUtil.isNotEmpty(taskOrder.getNums())) {
    				BigDecimal nums = new BigDecimal(taskOrder.getNums());
    				if(nums.compareTo(as)==1) {
    					prescription = nums.divide(hours,2,BigDecimal.ROUND_HALF_DOWN);
        				for (TaskDetailedResult r : list) {
        					BigDecimal h = new BigDecimal(r.getHours());
    						r.setNums(prescription.multiply(h).setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());
    						ToolUtil.copyProperties(r, taskDetailedParam);
    						taskDetailedService.update(taskDetailedParam);
    					}
    				}
    			}
			}
    	}
    	if(taskOrder.getSettlementMode().equals("重量")) {//计算时效
    		if (list.size() >0) {
    			if (ToolUtil.isNotEmpty(taskOrder.getWeights())) {
    				BigDecimal weights = new BigDecimal(taskOrder.getWeights());
    				if(weights.compareTo(as)==1) {
    					prescription = weights.divide(hours,2,BigDecimal.ROUND_HALF_DOWN);
        				for (TaskDetailedResult r : list) {
        					BigDecimal h = new BigDecimal(r.getHours());
    						r.setWeights(prescription.multiply(h).setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());
    						ToolUtil.copyProperties(r, taskDetailedParam);
    						taskDetailedService.update(taskDetailedParam);
    					}
    				}
    			}
			}
    	}
    	
    	taskOrderParam.setHours(hours.toString());//更新作业单
    	taskOrderParam.setPrescription(prescription.toString());
		taskOrderParam.setV6("0");
    	taskOrderService.update(taskOrderParam);
        return ResponseData.success();
    }

    @Autowired
    private BasicCustomerService basicCustomerService;

    @Autowired
    private BasicOperateService basicOperateService;

    /**
     * 新增页面
     */
    @RequestMapping("/add")
    public String add(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/taskOrder_add.html";
    }

    /**
     * 打印作业单
     */
    @RequestMapping("/toprinting")
    public String toprinting(TaskOrderParam taskOrderParam,Model model) {
    	TaskOrder taskOrder = taskOrderService.getById(taskOrderParam.getId());
    	if(taskOrder.getSettlementMode().equals("体积")) {
    		taskOrder.setV4(taskOrder.getVolume());
    	}
    	if(taskOrder.getSettlementMode().equals("数量")) {
    		taskOrder.setV4(taskOrder.getNums());
    	}
    	if(taskOrder.getSettlementMode().equals("重量")) {
    		taskOrder.setV4(taskOrder.getWeights());
    	}
    	model.addAttribute("taskOrder", taskOrder);
        return PREFIX + "/printing.html";
    }

    /**
     * 打印二维码
     */
    @RequestMapping("/toqrCode")
    public String toqrCode(TaskOrderParam taskOrderParam,Model model) {
    	TaskOrder taskOrder = taskOrderService.getById(taskOrderParam.getId());
    	if(taskOrder.getSettlementMode().equals("体积")) {
    		taskOrder.setV4(taskOrder.getVolume());
    	}
    	if(taskOrder.getSettlementMode().equals("数量")) {
    		taskOrder.setV4(taskOrder.getNums());
    	}
    	if(taskOrder.getSettlementMode().equals("重量")) {
    		taskOrder.setV4(taskOrder.getWeights());
    	}
    	model.addAttribute("taskOrder", taskOrder);
        return PREFIX + "/qrCode.html";
    }

    /**
     * 打印面单
     */
    @RequestMapping("/tomiandanqrCode")
    public String tomiandanqrCode(TaskOrderParam taskOrderParam,Model model) {
    	TaskOrder taskOrder = taskOrderService.getById(taskOrderParam.getId());
    	if(taskOrder.getSettlementMode().equals("体积")) {
    		taskOrder.setV4(taskOrder.getVolume());
    	}
    	if(taskOrder.getSettlementMode().equals("数量")) {
    		taskOrder.setV4(taskOrder.getNums());
    	}
    	if(taskOrder.getSettlementMode().equals("重量")) {
    		taskOrder.setV4(taskOrder.getWeights());
    	}
    	model.addAttribute("taskOrder", taskOrder);
        return PREFIX + "/miandanqrCode.html";
    }


    /**
     * 创建二维码
     */	
    @RequestMapping(value = "/getqrcode", method = RequestMethod.GET)
    @ResponseBody
    public void generateQRCode4Product(String id,String name, HttpServletRequest request, HttpServletResponse response) {
        try {
            //logo
            File logoFile = new File("");

            String url = "qrcode-56it-"+id;

            QRCodeUtil.drawLogoQRCode(logoFile, url, name,350,350,request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 创建二维码面单
     */	
    @RequestMapping(value = "/getqrcodemiandan", method = RequestMethod.GET)
    @ResponseBody
    public void generateQRCode4Product2(String id,String name, HttpServletRequest request, HttpServletResponse response) {
        try {
            //logo
            File logoFile = new File("");

            String url = "qrcode-56it-"+id;

            QRCodeUtil2.drawLogoQRCode(logoFile, url, name,request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 编辑页面
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/taskOrder_edit.html";
    }

    /**
     * 新增接口
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(TaskOrderParam taskOrderParam,String type1,String type2,String type3,String type4,String type5,String type6,String type7,String type8,String type9) {
    	ResponseData data = new ResponseData();
    	if(!taskOrderParam.getTaskWork().equals("卸车")&&!taskOrderParam.getTaskWork().equals("装车")) {
    		taskOrderParam.setCarModel("");
    	}
    	if(taskOrderParam.getTaskWork().equals("卸车")) {
			if (ToolUtil.isEmpty(taskOrderParam.getCustomerNumber())) {
				data.setSuccess(false);
				data.setMessage("客户单号不得为空");
				return data;
			}
    		taskOrderParam.setV8(type1);
    	}
    	if(taskOrderParam.getTaskWork().equals("装车")) {
			if (ToolUtil.isEmpty(taskOrderParam.getCustomerNumber())) {
				data.setSuccess(false);
				data.setMessage("客户单号不得为空");
				return data;
			}
    		taskOrderParam.setV8(type2);
    	}
    	if(taskOrderParam.getTaskWork().equals("入库")) {
    		taskOrderParam.setV8(type3);
    	}
    	if(taskOrderParam.getTaskWork().equals("移库")) {
    		taskOrderParam.setV8(type4);
    	}
    	if(taskOrderParam.getTaskWork().equals("领料")) {
    		taskOrderParam.setV8(type5);
    	}
    	if(taskOrderParam.getTaskWork().equals("废料")) {
    		taskOrderParam.setV8(type6);
    	}
    	if(taskOrderParam.getTaskWork().equals("理库")) {
    		taskOrderParam.setV8(type7);
    	}
    	if(taskOrderParam.getTaskWork().equals("批量作业")) {
    		taskOrderParam.setV8(type8);
    	}
    	if(taskOrderParam.getTaskWork().equals("杂工")) {
    		taskOrderParam.setV8(type9);
    	}
    	if(ToolUtil.isNotEmpty(taskOrderParam.getCustomerNumber())) {
    		taskOrderParam.setCustomerNumber("'"+taskOrderParam.getCustomerNumber()+"'");
    	}
    	if(taskOrderParam.getTaskWork().equals("跟车")) {
			if (ToolUtil.isEmpty(taskOrderParam.getV9())) {
				data.setSuccess(false);
				data.setMessage("请输入门店数");
				return data;
			}
    	}
    	if (taskOrderParam.getSettlementMode().equals("体积")) {
			if (ToolUtil.isEmpty(taskOrderParam.getVolume())) {
				data.setSuccess(false);
				data.setMessage("体积不得为空");
				return data;
			}
		}
    	if (taskOrderParam.getSettlementMode().equals("数量")) {
			if (ToolUtil.isEmpty(taskOrderParam.getNums())) {
				data.setSuccess(false);
				data.setMessage("数量不得为空");
				return data;
			}
		}
    	if (taskOrderParam.getSettlementMode().equals("重量")) {
			if (ToolUtil.isEmpty(taskOrderParam.getWeights())) {
				data.setSuccess(false);
				data.setMessage("重量不得为空");
				return data;
			}
		}
    	DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMdd");//设置日期格式
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	BasicCustomer basicCustomer = basicCustomerService.getById(taskOrderParam.getOutCustomerId());
    	taskOrderParam.setOutCustomerName(basicCustomer.getCustomerName());
    	BasicOperate basicOperate = basicOperateService.getById(taskOrderParam.getOperateId());
    	taskOrderParam.setOperateName(basicOperate.getOperateName());
    	taskOrderParam.setStatus("未开始");
    	TaskOrderParam to = new TaskOrderParam();
    	to.setV1(DateUtil.getDate());
    	to.setDeptId(deptId);
    	to.setDeliverId(deliverId);
    	int count = taskOrderService.countBydate(to,user.getOperateId());
    	taskOrderParam.setOrderNumber(user.getAccount().substring(0, 3)+LocalDateTime.now().format(fmt)+(count+1));
    	taskOrderParam.setDeptId(deptId);
    	taskOrderParam.setDeliverId(deliverId);
    	taskOrderParam.setV2(DateUtil.getDateS());
    	taskOrderParam.setV3(user.getName());
    	taskOrderParam.setPeoples("0");
    	taskOrderParam.setV6("0");
    	taskOrderParam.setV7(user.getUserId()+"");
        this.taskOrderService.add(taskOrderParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(TaskOrderParam taskOrderParam) {
        this.taskOrderService.update(taskOrderParam);
        return ResponseData.success();
    }

    /**
     * 作废接口
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(TaskOrderParam taskOrderParam) {
    	taskOrderParam.setStatus("作废");
    	taskOrderParam.setV4(DateUtil.getDateS());
    	taskOrderParam.setV5(userService.getcurrentUser().getName());
        this.taskOrderService.update(taskOrderParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(TaskOrderParam taskOrderParam) {
        TaskOrder detail = this.taskOrderService.getById(taskOrderParam.getId());
        return ResponseData.success(detail);
    }
    
    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(TaskOrderParam taskOrderParam,String condition ,String startTime,String endTime,String startTime2,String endTime2
    		,String type1,String type2,String type3,String type4,String type5,String type6,String type7,String type8,String type9) {
    	if(ToolUtil.isNotEmpty(taskOrderParam.getTaskWork())) {
    		if(taskOrderParam.getTaskWork().equals("卸车")) {
    			taskOrderParam.setV8(type1);
    		}
    		if(taskOrderParam.getTaskWork().equals("装车")) {
    			taskOrderParam.setV8(type2);
    		}
    		if(taskOrderParam.getTaskWork().equals("入库")) {
    			taskOrderParam.setV8(type3);
    		}
    		if(taskOrderParam.getTaskWork().equals("移库")) {
    			taskOrderParam.setV8(type4);
    		}
        	if(taskOrderParam.getTaskWork().equals("领料")) {
        		taskOrderParam.setV8(type5);
        	}
        	if(taskOrderParam.getTaskWork().equals("废料")) {
        		taskOrderParam.setV8(type6);
        	}
        	if(taskOrderParam.getTaskWork().equals("理库")) {
        		taskOrderParam.setV8(type7);
        	}
        	if(taskOrderParam.getTaskWork().equals("批量作业")) {
        		taskOrderParam.setV8(type8);
        	}
        	if(taskOrderParam.getTaskWork().equals("杂工")) {
        		taskOrderParam.setV8(type9);
        	}
    	}
    	if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
    		taskOrderParam.setV1("'"+startTime+"' and '"+endTime+"'");
		}
    	if (ToolUtil.isNotEmpty(startTime2) && ToolUtil.isNotEmpty(endTime2)) {
    		taskOrderParam.setCreateTimes("'"+startTime2+"' and '"+endTime2+"'");
		}
    	User user = userService.getcurrentUser();
    	taskOrderParam.setDeliverId(user.getDeliverId());
    	taskOrderParam.setDeptId(user.getDeptId());
//    	if(CangGuanRoleId.CGRoleId.longValue() != 0l) {
//    		String[] split = user.getRoleId().split(",");//以逗号分割
//    		for (String string2 : split) {
//    			Long cgRole = CangGuanRoleId.CGRoleId;
//    			Long userR = Long.parseLong(string2);
//    			if (userR.longValue() == cgRole.longValue()) {
//    				taskOrderParam.setV7(user.getUserId()+"");
//    			}
//    		}
//    	}
        return this.taskOrderService.findPageBySpec(taskOrderParam,condition,user.getOperateId());
    }

}


